package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/*
 *@AUTHOR:LIUCHAO;
 *@DATE: 2020/9/21 20:14
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    private MenuService menuService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;/*passwordEncoder.encode()使用bcrypt提供的方法对密码进行加密*/
    @RequestMapping("/getMenu")
    public Result getMenu() {
        org.springframework.security.core.userdetails.User user =
                (org.springframework.security.core.userdetails.User)
                        SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = user.getUsername();
      List<Menu> list= menuService.findMenu(username);
      List<Menu> data= new ArrayList<>();
        for (Menu menu : list) {
            if (menu.getPath().startsWith("/")){
                continue;
            }
            if (!menu.getPath().startsWith("/")){
                List<Menu> children = new ArrayList<>();
                for (Menu menuChild : list) {
                    System.out.println(menu.getId());
                    System.out.println(menuChild.getParentMenuId());
                   if (menuChild.getParentMenuId()==menu.getId()){
                       children.add(menuChild);
                   }
                }
                menu.setChildren(children);
            }
            data.add(menu);
        }
        return new Result(true, "导入菜单成功",data);
    }

    public List<Menu> menuList(List<Menu> list){
        List<Menu> data= new ArrayList<>();
        for (Menu menu : list) {
            if (menu.getPath().startsWith("/")){
                continue;
            }
            if (!menu.getPath().startsWith("/")){
                List<Menu> children = new ArrayList<>();
                for (Menu menuChild : list) {
                    System.out.println(menu.getId());
                    System.out.println(menuChild.getParentMenuId());
                    if (menuChild.getParentMenuId()==menu.getId()){
                        children.add(menuChild);
                    }
                }

                menu.setChildren(children);
                data.add(menu);
            }
        }

        /*==============*/

        return data;
    }


}
